package JUC.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 异步调用：CompletableFuture
 */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //发起一个请求
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "runAsync=>void");
        });

        //获取执行结果
        completableFuture.get();


        //有返回值的异步回调
        //ajax,success,fail回调
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            return 1024;
        });


        integerCompletableFuture.whenComplete((t, u)->{
            System.out.println(t+","+u);//错误信息
        }).exceptionally((exception)->{
            System.out.println(exception.getMessage());
            return 233;//可以获取错误返回结果
//            exception.printStackTrace();

        }).get();
    }
}
